package cn.tedu.order.controller;

import cn.tdu.common.result.JsonResult;
import cn.tedu.order.service.OrderService;
import cn.tedu.pojo.param.OrderAddParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 订单控制层
 */
@RestController
@Slf4j
@RefreshScope//在需要实现动态刷新的类上添加
public class OrderController {

    @Value("${order.name}")
    private String orderName;
    @Autowired
    private OrderService orderService;

    /**
     * 添加订单
     * @param orderAddParam
     * @return
     */
    @PostMapping("/order/add")
    public JsonResult addOrder(OrderAddParam orderAddParam){
        log.info("开始处理添加订单的请求，参数：orderAddParam={}",orderAddParam);
        // 参数校验
        if (orderAddParam == null) {
            log.warn("订单参数不能为空");
            return JsonResult.fail("订单参数不能为空");
        }

        if (orderAddParam.getProductCode() == null || orderAddParam.getProductCode().trim().isEmpty()) {
            log.warn("商品编码不能为空");
            return JsonResult.fail("商品编码不能为空");
        }

        if (orderAddParam.getUserId() == null || orderAddParam.getUserId().trim().isEmpty()) {
            log.warn("用户ID不能为空");
            return JsonResult.fail("用户ID不能为空");
        }

        if (orderAddParam.getCount() == null || orderAddParam.getCount() <= 0) {
            log.warn("商品数量必须大于0");
            return JsonResult.fail("商品数量必须大于0");
        }

        try {
            // 调用业务层
            Boolean result = orderService.addOrder(orderAddParam);
            log.info("处理添加订单的请求结果：result={}", result);
            if (!result){
                log.info("添加订单失败");
                return JsonResult.fail("添加订单失败");
            }
            log.info("添加订单成功");
            return JsonResult.ok("ok");
        } catch (Exception e) {
            log.error("添加订单时发生异常：", e);
            return JsonResult.fail("系统繁忙，请稍后再试");
        }
    }

    @GetMapping("/get/orderName")
    public JsonResult getOrderName(){
        log.info("开始处理获取订单名称的请求");
        return JsonResult.ok(orderName);
    }
}